package com.boomsecret.threadtransfer;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author wangjinliang on 2019/1/31.
 */
public class ConditionAwaitSignalDemo {
    private static ReentrantLock reentrantLock;
    private static Condition condition;

    static {
        reentrantLock = new ReentrantLock();
        condition = reentrantLock.newCondition();
    }

    public static void main(String[] args) {
        ThreadA threadA = new ThreadA();
        ThreadB threadB = new ThreadB();

        threadA.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        threadB.start();
    }

    public static class ThreadA extends Thread {
        @Override
        public void run() {
            reentrantLock.lock();
            System.out.println("threadA start.");
            try {
                condition.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("threadA end.");
            reentrantLock.unlock();
        }
    }

    public static class ThreadB extends Thread {
        @Override
        public void run() {
            reentrantLock.lock();
            System.out.println("threadB start.");
            condition.signal();
            System.out.println("threadB end.");
            reentrantLock.unlock();
        }
    }
}
